from datetime import datetime
from django import forms
from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.contrib.sites.models import Site
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template.defaultfilters import slugify
from django.utils.translation import gettext as _
from models import Photo

@login_required
def add_edit_photo(request, id=None):
    if id is None:
        PhotoForm = forms.models.form_for_model(Photo)
    else:
        pic = Photo.objects.get(id=id)
        PhotoForm = forms.models.form_for_instance(pic)

    # These widgets are shown in the Admin view, but not needed by
    # regular users.
    PhotoForm.base_fields['user'].widget = forms.widgets.HiddenInput()
    PhotoForm.base_fields['user'].required = False
    PhotoForm.base_fields['site'].widget = forms.widgets.HiddenInput()
    PhotoForm.base_fields['site'].required = False
    PhotoForm.base_fields['pub_date'].widget = forms.widgets.HiddenInput()
    PhotoForm.base_fields['pub_date'].required = False
    PhotoForm.base_fields['slug'].widget = forms.widgets.HiddenInput()
    PhotoForm.base_fields['slug'].required = False
    PhotoForm.base_fields['photographer'].required = False
    PhotoForm.base_fields['caption'].required = False
    
    if request.method == 'POST':
        post_data = request.POST.copy()
        post_data.update(request.FILES)
        form = PhotoForm(request.POST, request.FILES)
        if form.is_valid():
            pic = form.save(commit=False)
            # The current site we're uploading from
            pic.site = Site.objects.get(id=settings.SITE_ID)
            pic.user = request.user
            pic.pub_date = datetime.now()
            pic.slug = slugify(pic.title)
            pic.save()
            return HttpResponseRedirect(pic.get_absolute_url())
    else:
        form = PhotoForm()

    return render_to_response('photos/photo_add.html', {'form': form})

